package main

import (
	"ai-gateway/adapters"
	_ "ai-gateway/adapters" // 初始化适配器注册
	"ai-gateway/common"
	"ai-gateway/config"
	"ai-gateway/db"
	"ai-gateway/proto"
	"context"
	"fmt"
	"net"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

type AdapterServer struct {
	proto.UnimplementedAdapterServiceServer
}

func (s *AdapterServer) CallAI(ctx context.Context, req *proto.AIRequest) (*proto.AIResponse, error) {
	// 从路由服务获取推荐的服务商
	routeAddr := fmt.Sprintf("%s:%d", config.Config.ServiceIP, config.Config.RouteServicePort)
	routeConn, err := grpc.Dial(routeAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return &proto.AIResponse{}, fmt.Errorf("连接路由服务失败: %v", err)
	}
	defer routeConn.Close()
	routeClient := proto.NewRouteServiceClient(routeConn)

	routeResp, err := routeClient.SelectProvider(ctx, req)
	if err != nil {
		return &proto.AIResponse{}, fmt.Errorf("路由决策失败: %v", err)
	}

	// 从注册中心获取适配器-根据从路由服务中提取出来的provider
	adapter, ok := adapters.AdapterRegistry[routeResp.Provider]
	if !ok {
		return &proto.AIResponse{Result: "不支持的服务商: " + routeResp.Provider}, nil
	}

	// 调用适配器
	return adapter.Call(ctx, req)
}

// 流式调用方法
func (s *AdapterServer) StreamCallAI(req *proto.AIRequest, stream proto.AdapterService_StreamCallAIServer) error {
	// 调用路由服务获取厂商
	routeAddr := fmt.Sprintf("%s:%d", config.Config.ServiceIP, config.Config.RouteServicePort)
	routeConn, err := grpc.Dial(routeAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return fmt.Errorf("连接路由服务失败: %v", err)
	}
	defer routeConn.Close()
	routeClient := proto.NewRouteServiceClient(routeConn)

	routeResp, err := routeClient.SelectProvider(stream.Context(), req)
	if err != nil {
		return fmt.Errorf("路由失败: %v", err)
	}
	provider := routeResp.Provider

	// 获取流式适配器
	adapter, ok := adapters.StreamAdapterRegistry[provider]
	if !ok {
		return fmt.Errorf("厂商 %s 不支持流式调用", provider)
	}

	// 调用适配器的流式方法
	return adapter.StreamCall(stream.Context(), req, stream)
}

func main() {
	common.InitLogger("adapter-service")
	if err := db.InitDB(); err != nil {
		common.Logger.Fatal().Err(err).Msg("数据库初始化失败")
	}

	lis, err := net.Listen("tcp", fmt.Sprintf("%s%d", ":", config.Config.AdapterServicePort))
	if err != nil {
		common.Logger.Fatal().Err(err).Msg("监听端口失败")
	}

	s := grpc.NewServer()
	proto.RegisterAdapterServiceServer(s, &AdapterServer{})
	common.Logger.Info().Msg("Adapter Service 启动: :8081")

	if err := s.Serve(lis); err != nil {
		common.Logger.Fatal().Err(err).Msg("服务启动失败")
	}
}
